package com.ferry.controller;

import com.ferry.service.AdminService;
import com.ferry.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@Slf4j
public class LoginController {

    @Autowired
    private AdminService adminService;

    @GetMapping({"/","/home","/index"})
    public String home(HttpServletRequest request,Model model) {
        log.info("时间:" + DateUtils.getCurrentDate() + ",IP:" + IpUtils.getIpAddress(request) + "访问首页！");
        model.addAttribute("logged",false);
        return "index";
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request) {
        log.info("时间:" + DateUtils.getCurrentDate() + ",IP:" + IpUtils.getIpAddress(request) + "访问登陆页面！");
        return "login";
    }

    @PostMapping("/login")
    public String login(String email, String password, Model model, HttpSession session) {

        log.info("邮箱:" + email +",密码:" + password + "登陆了");

        if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
            if (EmailUtils.isValidEmail(email)) {
                Response login = adminService.login(email, password);
                if (login.getCode() == ResponseGenerator.success) {
                    model.addAttribute("msg",login.getMassage());
                    model.addAttribute("admin",login.getResponse());
                    model.addAttribute("logged",true);
                    session.setAttribute("admin",login.getResponse());
                    return "index";
                } else {
                    model.addAttribute("msg",login.getMassage());
                    return "login";
                }
            } else {
                model.addAttribute("msg","请输入有效的邮箱");
                return "login";
            }
        } else {
            model.addAttribute("msg","邮箱或密码不能为空");
            return "login";
        }
    }


}
